// pages/goods-more-lists/index.js
import {
    getNavigationbar,
} from "../../api/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navigateName: "",
        scrollViewHeight: 0,
        numGood: 0,
        isSpecs: false,
        goodsList: [],
        obj: {},
        districtInfo: null,
        cartGoodDetail: {}, //购物车商品数据
        params: {},
        isAhow: false,
        goodListP: 1,

    },
    nood() {
        console.log('点击', this.data.subdata)
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        wx.reLaunch({
            url: `/pages/goods_cart/index`,
        })

    },
    getShoppingCartList(item) {
        getNavigationbar({
            act: 'getcartsp',

        }).then(res => {
            console.log('购物车列表-一件代发', res)
            this.setData({
                numGood: res.numbers
            })

        });
    },
    /**
     * 根据路由跳转名称获取对应商品列表
     * @param {*} name 
     */
    getGoodsList(params) {
        const {
            name,
            value
        } = params
        switch (name) {
            case '单品促销':
                this.getHttpGoodsList({
                    act: 'unique_product_list',
                    lack_inventory: 1,
                    p: this.data.goodListP
                })
                break;
            case '主粮':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.district_id,
                    p: this.data.goodListP
                })
                break;
            case '零食':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.district_id,
                    p: this.data.goodListP
                })
                break;
            case '用品':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.district_id,
                    p: this.data.goodListP
                })
                break;
            case '营养保健':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.district_id,
                    p: this.data.goodListP
                })
                break;
            case '9.9':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.activeid,
                    p: this.data.goodListP
                })
                break;
            case '9.6':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.activeid,
                    p: this.data.goodListP
                })
                break;
            case '药品专区':
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.activeid,
                    p: this.data.goodListP
                })
                break;
            case name:
                this.getHttpGoodsList({
                    act: 'district_detail',
                    lack_inventory: 1,
                    district_id: value.activeid || value.district_id,
                    p: this.data.goodListP
                })
                break;
        }
    },
    /**
     * 执行请求获取数据回调方法数据
     */
    getHttpGoodsList(params) {
        console.log('1', params)
        getNavigationbar(params).then(res => {
            if (res) {
                console.log('getHttpGoodsList', res)
                if (res.result == 101) {
                    return wx.showModal({
                        title: '',
                        content: res.msg,
                        showCancel: false, // 是否显示取消按钮，设为false表示不显示
                        confirmText: '确定', // 确定按钮的文本
                        success(res) {
                            if (res.confirm) {
                                wx.navigateBack()
                            }
                        }
                    });
                }
                console.log('params.act', params.act)
                switch (params.act) {

                    case 'unique_product_list':
                        res.forEach(element => {
                            if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                                element.sellprice = '***'
                                element.marketprice = '***'
                                element.real_price = '***'
                            }
                        });
                        wx.nextTick(() => {
                            const result = res.map(obj => {
                                const uniqueIds = [...new Set(obj.activity.map(item => item.range))];
                                const filteredActive = uniqueIds.map(range => obj.activity.filter(item => item.range === range).pop());
                                return {
                                    ...obj,
                                    activity: filteredActive.reverse()
                                };
                            });
                            this.setData({
                                goodsList: this.data.goodsList.concat(result),
                                districtInfo: null
                            }, () => {
                                this.computeScrollViewHeight() // 重新执行页面计算
                            })
                        })
                        break;
                    case 'district_detail':
                        res.goods.forEach(element => {
                            if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                                element.sellprice = '***'
                                element.marketprice = '***'
                                element.real_price = '***'
                            }
                        });
                        wx.nextTick(() => {
                            let arr = res.goods.length ? res.goods : res.ad_list

                            arr = arr.map(obj => {
                                const uniqueIds = [...new Set(obj.activity_list?.map(item => item.range))];
                                const filteredActive = uniqueIds.map(range => obj.activity_list.filter(item => item.range === range).pop());
                                return {
                                    ...obj,
                                    activity: filteredActive.reverse()
                                };
                            });
                            this.setData({
                                goodsList: this.data.goodsList.concat(arr),
                                districtInfo: {
                                    name: res.name,
                                    state: res.state,
                                    style: res.style,
                                    thumb: res.thumb,
                                    bg_color: res.bg_color
                                },
                                navigateName: res.name
                            }, () => {
                                this.computeScrollViewHeight() // 重新执行页面计算
                            })
                        })
                        break;
                }

            }
        })
    },
    /**
     * 根据条件跳转各项活动专区回调函数方法
     */
    handleRegionEntry(e) {
        const {
            value,
            name
        } = e.currentTarget.dataset;
        let num = value.type
        let id = value.type
        const params = {
            name: value.name,
            value: value
        }
        console.log('点击', num, e.currentTarget)
        // 根据类型判断跳转到具体的链接
        if (num == 1 && name == '新品') {
            params.name = '9.8'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        // 根据类型判断跳转到具体的链接
        if (num == 2) {
            params.name = '特卖专区'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        if (num == 4) {
            // params.name = '特卖专区'
            params.value.goodsId = params.value.goodsid
            params.value.detailType = 1,
                params.value.act = "good_detail"

            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
            })
        }
        // 根据类型及活动ID同时判断前往对应条件页
        if (num == 3 && value.activeid) {
            let obj = {
                ...value,
            }
            obj.name = obj.brandname
           
            let objStr = encodeURIComponent(JSON.stringify(obj));
            wx.navigateTo({
                url: '/pages/goods_list/index?obj=' + objStr,
            })
        }
        if (num == 7) {
            wx.navigateTo({
                url: `/pages/new_born_zone/index?data=${JSON.stringify(params)}`,
            })
        }
        // 根据类型判断前往新品专区
        if (num == 8) {
            params.name = '新品专区'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        if (num == 9) {
            params.name = '特卖专区'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        if (num == 10) {
            params.name = '限时秒杀'
            wx.navigateTo({
                url: `/pages/mall_flash_sale/index?data=${JSON.stringify(params)}`,
            })
        }
        if (num == 11) {
            params.name = '品牌促销'
            wx.navigateTo({
                url: `/pages/brand_list/index?data=${JSON.stringify(params.value)}`,
            })
        }
        if (num == 12) {
            params.name = '换购专区'
            wx.navigateTo({
                url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
            })
        }
        if (num == 13) {
            let  title='优惠券专区'
            // params.name = '优惠券专区'
            wx.navigateTo({
                url: `/pages/coupon/index?title=${title}`,
            })
        }
        // 根据类型判断前往一件代发
        if (num == 14) {
            let obj = {
                ...params,
                shipping: true
            }
            obj.bcat_list = []
            let objStr = encodeURIComponent(JSON.stringify(obj));
            wx.navigateTo({
                url: '/pages/goods_list/index?obj=' + objStr,
            })
        }

        if (num == 17) {

            params.value.goodsId = params.value.goodsid
            params.value.detailType = 1,
                params.value.lack_inventory = 1,
                params.value.act = "special_sales_detail"

            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
            })
        }
        if (num == 16) {

            params.value.goodsId = params.value.goodsid
            params.value.detailType = 10,
                params.value.act = "seckill_detail"

            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
            })
        }

        if (num == 18) {

            params.value.goodsId = params.value.goodsid
            params.value.detailType = 7,
                params.value.act = "unconsume_region_detail"

            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
            })
        }
        if (num == 19) {

            params.value.goodsId = params.value.goodsid
            params.value.detailType = 8,
                params.value.lack_inventory = 1,
                params.value.act = "new_goods_region_detail"

            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
            })
        }
        // 根据类型及活动ID同时判断前往对应条件页
        if (num == 20 && value.activeid) {
            wx.navigateTo({
                url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
            })
        }
    },
    goodsDetailFn(e) {
        console.log('e', e, this.data.districtInfo.style)
        const value = e.currentTarget.dataset.value

        let num = value.type
        let id = value.type
        const params = {
            name: value.name,
            value: value
        }
        if (this.data.districtInfo.style == 2) {
            this.handleRegionEntry(e)
        }
        // if (this.data.districtInfo.style == 2 && value.type == 4) {
        //     // params.name = '特卖专区'
        //     params.value.goodsId = params.value.goodsid
        //     params.value.detailType = 1,
        //         params.value.act = "good_detail"

        //     wx.navigateTo({
        //         url: `/pages/goods_detail/index?data=${JSON.stringify(params.value)}`,
        //     })
        // }
        // if (value.activeid && this.data.districtInfo.style == 2) {
        //     const params = {
        //         name: '',
        //         value: value
        //     }
        //     wx.navigateTo({
        //         url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
        //     })
        // }

        // if (this.data.districtInfo.style == 2 && value.type == 14) {
        //     let obj = {
        //         ...value,
        //         type: 'Issuing',
        //         shipping: true,
        //         brand_list: [{
        //             brandid: value.brandid,
        //             id: value.id,
        //             name: value.brandname,
        //             status: 0,
        //             shipping: true,
        //             type: value.type
        //         }]

        //     }
        //     console.log('进')
        //     // obj.name = obj.brandname
        //     let objStr = encodeURIComponent(JSON.stringify(obj));
        //     wx.navigateTo({
        //         url: '/pages/goods_list/index?obj=' + objStr,
        //     })
        // }

        if (value.brandid && this.data.districtInfo.style == 2) {
            let obj = {
                ...value,
                type: 'Issuing',
                brand_list: [{
                    brandid: value.brandid,
                    id: value.brandid,
                    name: value.brandname,
                    status: 0,
                   
                    type: value.type
                }],
                bcat_list:[],
            }
            console.log('进',obj)
            // obj.name = obj.brandname
            let objStr = encodeURIComponent(JSON.stringify(obj));
            wx.navigateTo({
                url: '/pages/goods_list/index?obj=' + objStr,
            })
        }
        if (this.data.districtInfo.style == 3) {
            const params = {
                goodsId: value.id,
                act: 'good_detail',
                detailType: 1
            }
            wx.navigateTo({
                url: `/pages/goods_detail/index?data=${JSON.stringify(params)}`,
            })
        }
        if (this.data.districtInfo.style == 1) {
            const params = {
                name: '',
                value: value
            }
            wx.navigateTo({
                url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
            })
        }
    },

    /**
     * 跳转商品详情页回调函数方法
     */
    handleGoodsDetail(e) {
        console.log("跳转详情", e)
        const {
            value
        } = e.currentTarget.dataset

        const params = {
            goodsId: "",
            area: "",
            detailType: 1,
            act: "good_detail"
        }
        if (value) {
            const {
                goodsid,
                id
            } = e.currentTarget.dataset.value
            if (goodsid) {
                params.goodsId = goodsid
            } else {
                params.goodsId = id
            }
        } else {
            const {
                id
            } = e.detail
            params.goodsId = id
        }

        console.log("params", params)
        wx.navigateTo({
            url: `/pages/goods_detail/index?data=${JSON.stringify(params)}`,
        })
    },

    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.content').boundingClientRect()
        query.exec(res => {
            // 同步获取系统信息
            const systemInfo = wx.getSystemInfoSync();
            // 计算底部安全距离
            const safeBottom = systemInfo.screenHeight - systemInfo.safeArea.bottom;
            let contentHeight = res[0].height;
            that.setData({
                scrollViewHeight: contentHeight - safeBottom
            })
        })
    },
    /**
     * 选择商品规格加入购物车回调函数方法
     */
    handleJoinCart(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log("value", value)
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        getNavigationbar({
            act: 'good_detail',
            id: value.id
        }).then(res => {
            this.setData({
                isSpecs: true,
                cartGoodDetail: res
            })
        })

        console.log('cartGoodDetail', this.data.cartGoodDetail)
    },
    /**
     * 完成规格选择将商品添加至购物车
     */
    handleConfirm(e) {
        let data = e.detail

        console.log("data", data, data.data.property)
        // if (data.type == 1) {
        getNavigationbar({
            act: 'cart',
            id: data.commodityId || '',
            propertyid: data.data.propertyid || data.data.property[0].id || '',
            numbers: data.count || '',
        }).then(res => {
            console.log('添加购物车', res)
            if (res.result == 101) {
                wx.nextTick(() => {
                    getApp().Tips({
                        title: res.msg
                    })
                })
            } else {
                this.setData({
                    isSpecs: false,
                    cartGoodDetail: {}
                })
                wx.nextTick(() => {
                    getApp().Tips({
                        title: "商品已添加至购物车"
                    })
                })
            }
            this.getShoppingCartList()
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            this.setData({
                navigateName: params.name,
                params: params
            })
            console.log('进来', params)
            wx.nextTick(() => {
                this.getGoodsList({
                    name: params.name,
                    value: params.value,
                    goodListP: this.data.goodListP
                })
            })
        }
        let res = wx.getStorageSync('USER')
        console.log('setStorageSync', res)
        this.data.obj = res
        this.getShoppingCartList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    scrollToLower() {
        this.data.goodListP++
        wx.nextTick(() => {
            this.getGoodsList({
                name: this.data.navigateName,
                value: this.data.params.value,
                p: this.data.goodListP
            })
        })
    },
})